/**
 * Copyright (c) 2012-2012 YunZhiSheng(Shanghai) Co.Ltd. All right reserved.
 * @FileName : TalkService.java
 * @ProjectName : V Plus 1.0
 * @PakageName : cn.yunzhisheng.ishuoshuo.talk
 * @Author : Dancindream
 * @CreateDate : 2012-5-22
 */
package cn.yunzhisheng.vui.assistant.tv.talk;

import java.util.ArrayList;

import com.vst.pushlib.PopupScreen;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.widget.Toast;
import cn.yunzhisheng.common.net.Network;
import cn.yunzhisheng.common.util.LogUtil;
//import cn.yunzhisheng.tts.offline.basic.ITTSControl;
//import cn.yunzhisheng.tts.offline.basic.TTSFactory;
//import cn.yunzhisheng.tts.offline.basic.TTSPlayerListener;
import cn.yunzhisheng.vui.assistant.tv.session.SessionManager;
import cn.yunzhisheng.vui.assistant.tv.talk.ITalkService;
import cn.yunzhisheng.vui.assistant.IDataControl;
import cn.yunzhisheng.vui.assistant.IVoiceAssistantListener;
import cn.yunzhisheng.vui.assistant.VoiceAssistant;
import cn.yunzhisheng.vui.assistant.preference.SessionPreferenceOfIntent;
import cn.yunzhisheng.vui.assistant.preference.UserPreference;
import cn.yunzhisheng.vui.assistant.tv.WindowService;
import cn.yunzhisheng.vui.control.IControlOperate;
import cn.yunzhisheng.vui.server.IServerListener;
import cn.yunzhisheng.vui.server.IServerOperate;
import cn.yunzhisheng.vui.util.ControlKey;

@SuppressLint("HandlerLeak")
public class TalkService extends Service {
    public static final String TAG = "TalkService";
    public final static String EVENT_TTS_PLAY_BEGIN = "EVENT_TTS_PLAY_BEGIN";
    public final static String EVENT_TTS_BUFFER = "EVENT_TTS_BUFFER";
    public final static String EVENT_TTS_PLAY_END = "EVENT_TTS_PLAY_END";
    public final static String EVENT_TTS_CANCEL = "EVENT_TTS_CANCEL";

    public final static String MOBILE_CONTROL_CONNECTION = "MOBILE_CONTROL_CONNECTION";
    public final static String MOBILE_CONTROL_DISCONNECTION = "MOBILE_CONTROL_DISCONNECTION";

    public final static String TALK_EVENT_ON_INITDONE = "cn.yunzhisheng.intent.talk.onInitDone";
    public final static String TALK_EVENT_ON_RECORDING_START = "cn.yunzhisheng.intent.talk.onRecordingStart";
    public final static String TALK_EVENT_ON_START = "cn.yunzhisheng.intent.talk.onTalkStart";
    public final static String TALK_EVENT_ON_STOP = "cn.yunzhisheng.intent.talk.onTalkStop";
    public final static String TALK_EVENT_ON_CANCEL = "cn.yunzhisheng.intent.talk.onTalkCancel";
    public final static String TALK_EVENT_ON_SESSION_PROTOCAL = "cn.yunzhisheng.intent.talk.onSessionProtocal";
    public final static String TALK_EVENT_ON_UPDATE_VOLUME = "cn.yunzhisheng.intent.talk.onUpdateVolume";

    public final static String TALK_DATA_VOLUME = "cn.yunzhisheng.intent.talk.data.volume";

    public final static String TALK_DATA_PROTOCAL = "cn.yunzhisheng.intent.talk.data.protocal";

    public static final String PERMISSION_VOICE_COMMAND = "cn.yunzhisheng.permission.RECEIVE_VOICE_COMMAND";
    public static final String CATEGORY_VOICE_COMMAND = "cn.yunzhisheng.intent.category.VOICE_COMMAND";

    public static final String MSG_VIRTUAL_KEY = "cn.yunzhisheng.intent.virtualKey";
    public static final String KEY_CODE = "KEY_CODE";
    public static final String MSG_VIRTUAL_KEY_SERVER_ACTIVE = "MSG_VIRTUAL_KEY_SERVER_ACTIVE";

    public static String VOICE_TV_SERVER_IP = "";

    private static String INTERACTIVE_METHOD_SDK = "SDK";
    private static String INTERACTIVE_METHOD_INTENT = "INTENT";

    private VoiceAssistant mVoiceAssistant = null;
    private static IServerOperate mServerOperate = null;
    private static IControlOperate mControlOperate = null;
    // private ITTSControl mTTSPlayer = null;

    private static IDataControl mDataControl = null;
    private static ArrayList<String> mOnlineSupportList = null;
    private static ArrayList<String> mOfflineSupportList = null;

    private TalkService mTalkService = null;

    private Looper mServiceCompileLooper;

    private UserPreference mUserPreference;

    private boolean mInteractiveMethod;

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogUtil.d(TAG, "action:  " + action);
            if (Network.CONNECTIVITY_CHANGE_ACTION.equals(action)) {
                // 网络变化的时候会发送通知
                Network.checkNetworkConnected(context);
            } else if (MSG_VIRTUAL_KEY_SERVER_ACTIVE.equals(action)) {
                // 说明接受虚拟按键的服务存在
                LogUtil.e(TAG, "KEY_VIRTUAL_KEY_SERVER_ACTIVE....alive");
                mUserPreference.putBoolean(UserPreference.KEY_VIRTUAL_KEY_SERVER_ACTIVE, true);
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_START_SCANNER_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    mControlOperate.startScanner();
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_STOP_SCANNER_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    mControlOperate.stopScanner();
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_CONNECT_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        String ip = bundle.getString(SessionPreferenceOfIntent.KEY_IP);
                        Bundle extra = new Bundle();
                        extra.putString(SessionPreferenceOfIntent.KEY_IP, ip);
                        mControlOperate.connect(ip);
                    }
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_DISCONNECT_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    mControlOperate.disconnect();
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_START_MACHINE_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    mControlOperate.startMachine();
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_STOP_MACHINE_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    mControlOperate.stopMachine();
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_CONTROL_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        ControlKey key = (ControlKey) bundle
                                .getSerializable(SessionPreferenceOfIntent.KEY_CONTROL_TYPE);
                        mControlOperate.doControl(key);
                    }
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_VOLUME_TO_TV.equals(action)) {
                LogUtil.d(TAG, "volume : " + mControlOperate);
                if (mControlOperate != null) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        String act = bundle.getString(SessionPreferenceOfIntent.KEY_ACTION);
                        String volume = bundle.getString(SessionPreferenceOfIntent.KEY_VOLUME);
                        mControlOperate.doVolume(act, volume);
                    }
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_CHANNEL_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        String act = bundle.getString(SessionPreferenceOfIntent.KEY_ACTION);
                        String param = bundle.getString(SessionPreferenceOfIntent.KEY_PARAM);
                        mControlOperate.doChannel(act, param);
                    }
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_SEND_DATA_TO_SERVER_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        String data = bundle.getString(SessionPreferenceOfIntent.KEY_CUSTOM_DATA);
                        Bundle extra = new Bundle();
                        extra.putString(SessionPreferenceOfIntent.KEY_CUSTOM_DATA, data);
                        mControlOperate.sendCustomDataToServer(data);
                    }
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_START_CHECK_IP_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        ArrayList<String> ips = bundle.getStringArrayList(SessionPreferenceOfIntent.KEY_CHECK_IPS);
                        mControlOperate.startCheckIps(ips);
                    }
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_STOP_CHECK_IP_TO_TV.equals(action)) {
                if (mControlOperate != null) {
                    mControlOperate.stopCheckIps();
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_SERVER_START_TO_TV.equals(action)) {
                if (mServerOperate != null) {
                    mServerOperate.startServer();
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_SERVER_STOP_TO_TV.equals(action)) {
                if (mServerOperate != null) {
                    mServerOperate.stopServer();
                }
            } else if (SessionPreferenceOfIntent.OPERATE_ACT_SERVER_SEND_DATA_TO_CONTROL_TO_TV.equals(action)) {
                if (mServerOperate != null) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        String data = bundle.getString(SessionPreferenceOfIntent.KEY_CUSTOM_DATA);
                        mServerOperate.sendCustomDataToControl(data);
                    }
                }
            } else if (SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_START_TALK_TO_TV.equals(action)) {
                mTalkService.startTalk();
            } else if (SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_STOP_TALK_TO_TV.equals(action)) {
                mTalkService.stopTalk();
            } else if (SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_CANCEL_TALK_TO_TV.equals(action)) {
                mTalkService.cancelTalk();
            } else if (SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_PUT_CUSTOM_TEXT_TO_TV.equals(action)) {
                String text = intent.getExtras().getString(SessionPreferenceOfIntent.KEY_TEXT);
                mTalkService.putCustomText(text);
            } else if (SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_SET_PROTOCAL_TO_TV.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.KEY_PROTOCAL);
                mTalkService.setProtocal(protocal);
            } else if (SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_PLAY_TTS_TO_TV.equals(action)) {
                String tts = intent.getExtras().getString(SessionPreferenceOfIntent.KEY_TTS);
                mTalkService.playTTS(tts);
            } else if (SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_STOP_TTS_TO_TV.equals(action)) {
                mTalkService.stopTTS();
            } else if (SessionPreferenceOfIntent.ACT_COMPILE_GRAMMER_TO_TV.equals(action)) {
                String commands = intent.getExtras().getString(SessionPreferenceOfIntent.KEY_COMMANDS);
                boolean supportSystemCommand = intent.getExtras().getBoolean(
                        SessionPreferenceOfIntent.KEY_SUPPROT_SYSTEM_COMMAND);
                mVoiceAssistant.setCustomUserData(supportSystemCommand, commands);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_WAITING.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_WEATHER_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_WEB_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_TRANSLATION_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_STOCK_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_MUSIC_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_PROG_RECOMMEND.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_PROG_SEARCH_RESULT.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_CHANNEL_PROG_LIST.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_ROUTE_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_POSITION_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_TALK_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_ERROR_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_APP_LAUNCH.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_APP_UNINSTALL.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_APP_EXIT.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_SETTING.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_REMINDER_CONFIRM.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_REMINDER_OK.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_POI_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_MULTIPLE_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_UI_HANDLE_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_NOTE_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_ALARM_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_APP_MUTIPLEP_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_INPUT_CONTENT_WEIBO.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_WEIBO_OK.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_CHANNEL_SWITCH_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            } else if (SessionPreferenceOfIntent.VALUE_TYPE_SHOP_SHOW.equals(action)) {
                String protocal = intent.getExtras().getString(SessionPreferenceOfIntent.TALK_PROTACAL);
                mTalkService.onSessionProtocal(protocal);
            }
        }

    };

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            Toast.makeText(mTalkService, msg.obj + "", Toast.LENGTH_LONG).show();

        };
    };

    private final ITalkService.Stub mBinder = new ITalkService.Stub() {

        @Override
        public void startTalk() throws RemoteException {
            mTalkService.startTalk();
        }

        @Override
        public void stopTalk() throws RemoteException {
            mTalkService.stopTalk();
        }

        @Override
        public void cancelTalk() throws RemoteException {
            mTalkService.cancelTalk();
        }

        @Override
        public void putCustomText(String text) throws RemoteException {
            mTalkService.putCustomText(text);
        }

        @Override
        public void setProtocal(String protocal) throws RemoteException {
            mTalkService.setProtocal(protocal);
        }

        @Override
        public void playTTS(String tts) throws RemoteException {
            TalkService.this.playTTS(tts);
        }

        @Override
        public void stopTTS() throws RemoteException {
            TalkService.this.stopTTS();
        }
    };

    private IVoiceAssistantListener mVoiceAssistantListener = new IVoiceAssistantListener() {

        @Override
        public void onVolumeUpdate(int arg0) {
            // PrivatePreference.mRecordingVoiceVolumn = (float) arg0;
            mTalkService.onUpdateVolume(arg0);
        }

        @Override
        public void onCancel() {
            mTalkService.onTalkCancel();
        }

        @Override
        public void onInitDone() {
            if (mVoiceAssistant != null) {
                mDataControl = mVoiceAssistant.getDataControl();
                mOnlineSupportList = mVoiceAssistant.getSupportList(true);
                mOfflineSupportList = mVoiceAssistant.getSupportList(false);
            }
            showMessage(TALK_EVENT_ON_INITDONE);
        }

        @Override
        public void onProtocal(String arg0) {
        }

        @Override
        public void onSessionProtocal(String arg0) {
            mTalkService.onSessionProtocal(arg0);
        }

        @Override
        public void onStart() {
            mTalkService.onTalkStart();
        }

        @Override
        public void onStop() {
            mTalkService.onTalkStop();
        }

        @Override
        public void onRecordingStart() {
            mTalkService.onRecordingStart();
        }

        @Override
        public void onDataDone() {

        }

        @Override
        public void onResult(String arg0) {

        }
    };

    private IServerListener mServerListener = new IServerListener() {

        @Override
        public void onStopMachine() {
            mTalkService.exitAssistant();
        }

        @Override
        public void onStartMachine() {
            mTalkService.startAssistant();
        }

        @Override
        public void onDisconnectClient(String arg0) {
            mTalkService.onDisconnectClient(arg0);
        }

        @Override
        public void onControlDone(ControlKey arg0) {
            if (arg0.equals(ControlKey.Back)) {
                if (mUserPreference.getBoolean(UserPreference.KEY_VIRTUAL_KEY_SERVER_ACTIVE, false)) {
                    sendVirtualKeyMessage(KeyEvent.KEYCODE_BACK);
                } else {
                    mTalkService.onVirtureKeyBack();
                }
            } else if (arg0.equals(ControlKey.Center)) {
                if (mUserPreference.getBoolean(UserPreference.KEY_VIRTUAL_KEY_SERVER_ACTIVE, false)) {
                    sendVirtualKeyMessage(KeyEvent.KEYCODE_DPAD_CENTER);
                } else {
                    mTalkService.onVirtureKeyCenter();
                }
            } else if (arg0.equals(ControlKey.Down)) {
                if (mUserPreference.getBoolean(UserPreference.KEY_VIRTUAL_KEY_SERVER_ACTIVE, false)) {
                    sendVirtualKeyMessage(KeyEvent.KEYCODE_DPAD_DOWN);
                } else {
                    mTalkService.onVirtureKeyDown();
                }
            } else if (arg0.equals(ControlKey.Left)) {
                if (mUserPreference.getBoolean(UserPreference.KEY_VIRTUAL_KEY_SERVER_ACTIVE, false)) {
                    sendVirtualKeyMessage(KeyEvent.KEYCODE_DPAD_LEFT);
                } else {
                    mTalkService.onVirtureKeyLeft();
                }
            } else if (arg0.equals(ControlKey.Right)) {
                if (mUserPreference.getBoolean(UserPreference.KEY_VIRTUAL_KEY_SERVER_ACTIVE, false)) {
                    sendVirtualKeyMessage(KeyEvent.KEYCODE_DPAD_RIGHT);
                } else {
                    mTalkService.onVirtureKeyRight();
                }
            } else if (arg0.equals(ControlKey.Up)) {
                if (mUserPreference.getBoolean(UserPreference.KEY_VIRTUAL_KEY_SERVER_ACTIVE, false)) {
                    sendVirtualKeyMessage(KeyEvent.KEYCODE_DPAD_UP);
                } else {
                    mTalkService.onVirtureKeyUp();
                }
            }
        }

        @Override
        public void onConnectClient(String arg0) {
            mTalkService.onConnectClient(arg0);
        }

        @Override
        public void onReceivedCustomDataFromControl(String arg0) {
            if (arg0.startsWith("search:")) {
                SessionManager.customAction(TalkService.this, arg0.replaceFirst("search:", ""));
                return;
            } else if (arg0.startsWith("channel:")) {
                SessionManager.customAction(
                        TalkService.this,
                        SessionManager.getLiveIntent(SessionManager.getLiveId(TalkService.this,
                                String.format("%04d", Integer.parseInt(arg0.replaceFirst("channel:", ""))), false)));
                return;
            } else if (arg0.startsWith("volume:")) {
                changeVolume(TalkService.this, "0".equals(arg0.replaceFirst("volume:", "")));
                return;
            } else if (arg0.startsWith("chat:")) {
                Intent intent = new Intent(PopupScreen.POPSCREEN_SEMDMSG);
                intent.putExtra("msg", arg0.replaceFirst("chat:", ""));
                sendBroadcast(intent);
                return;
            }

            Intent intent = new Intent();
            intent.setAction(WindowService.PROTOCAL_CUSTOMER_DATA);
            intent.putExtra("data", arg0);
            sendBroadcast(intent);
        }

        @Override
        public void onChannelDone(String action, String arg1) {

        }

        @Override
        public void onVolumeDone(String action, String arg1) {
            LogUtil.d(TAG, "onVolumeDone   action: " + action + "volume : " + arg1);
            // if (ControlType.ACTION_INCREASE.equals(action)) {
            // // 音量增
            // int currentVolume = RomSystemSetting.RaiseOrLowerVolume(
            // TalkService.this, true, Integer.parseInt(arg1));
            // mUserPreference
            // .putInt(UserPreference.KEY_VOLUME, currentVolume);
            // } else if (ControlType.ACTION_DECREASE.equals(action)) {
            // // 音量减
            // int currentVolume = RomSystemSetting.RaiseOrLowerVolume(
            // TalkService.this, false, Integer.parseInt(arg1));
            // mUserPreference
            // .putInt(UserPreference.KEY_VOLUME, currentVolume);
            // } else if (ControlType.ACTION_MAX.equals(action)) {
            // // 设置最大音量
            // int currentVolume = RomSystemSetting
            // .setMaxVolume(TalkService.this);
            // mUserPreference
            // .putInt(UserPreference.KEY_VOLUME, currentVolume);
            // } else if (ControlType.ACTION_MIN.equals(action)) {
            // // 设置最小音量
            // int currentVolume = RomSystemSetting
            // .setMinVolume(TalkService.this);
            // mUserPreference
            // .putInt(UserPreference.KEY_VOLUME, currentVolume);
            // } else if (ControlType.ACTION_RESET.equals(action)) {
            // // 重置音量
            // int currentVolume = -1;
            // int lastVolumeValue = mUserPreference.getInt(
            // UserPreference.KEY_VOLUME, -1);
            // if (lastVolumeValue != -1) {
            // // currentVolume = RomSystemSetting.setVolume(
            // // TalkService.this, lastVolumeValue);
            // }
            // mUserPreference
            // .putInt(UserPreference.KEY_VOLUME, currentVolume);
            // } else if (ControlType.ACTION_SET.equals(action)) {
            // // 设置音量到某个值
            // // int currentVolume = RomSystemSetting.setVolume(
            // // TalkService.this, Integer.parseInt(arg1));
            // // mUserPreference
            // // .putInt(UserPreference.KEY_VOLUME, currentVolume);
            // }
        }

        @Override
        public void onError(int result, String msg) {
            LogUtil.d(TAG, "onError   " + result);
            Message message = new Message();
            message.obj = msg;
            mHandler.sendMessage(message);
        }

    };

    private void sendVirtualKeyMessage(int keyCode) {
        LogUtil.d(TAG, "sendVirtualKeyMessage   " + keyCode);
        Intent intent = new Intent();
        intent.setAction(MSG_VIRTUAL_KEY);
        intent.putExtra(KEY_CODE, keyCode);
        sendBroadcast(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.d(TAG, "onCreate");
        mTalkService = this;
        mUserPreference = new UserPreference(this);
        registReceiver();

        mVoiceAssistant = new VoiceAssistant(this);
        mVoiceAssistant.setListener(mVoiceAssistantListener);
        mVoiceAssistant.init();
        // cn.yunzhisheng.preference.PrivatePreference.setValue("default_city",
        // Util.getCurrentCity(this));
        mVoiceAssistant.setVadEnable(true);
        // micDialog = new MicrophoneRenderDialog(this);
        String method = cn.yunzhisheng.preference.PrivatePreference.getValue("interactive_method",
                INTERACTIVE_METHOD_SDK);
        if (method.equals(INTERACTIVE_METHOD_SDK)) {
            mInteractiveMethod = true;
        } else if (method.equals(INTERACTIVE_METHOD_INTENT)) {
            mInteractiveMethod = false;
        }
        // mTTSPlayer = TTSFactory.createTTSControl(this, "");
        // mTTSPlayer.setTTSListener(mListener);
        // mTTSPlayer.setType(2);
        // mTTSPlayer.setStreamType(AudioManager.STREAM_MUSIC);
        // new Thread(new Runnable() {
        // @Override
        // public void run() {
        // String folderFiles = getFilesDir().getAbsolutePath()
        // + File.separator;
        // // mTTSPlayer.initTTSEngine(TalkService.this, folderFiles);
        // }
        // }).start();

        mServerOperate = (IServerOperate) mVoiceAssistant.getServerOperate();
        if (mServerOperate != null) {
            mServerOperate.setServerListener(mServerListener);
        }

        // // 遥控器的句柄，电视端无效
        // mControlOperate =
        // (IControlOperate)mVoiceAssistant.getControlOperate();
        // if(mControlOperate != null){
        // mControlOperate.setControlListener(mControlListener);
        // }

        VOICE_TV_SERVER_IP = mServerOperate.getServerIpAddress();
        mServerOperate.setName(android.os.Build.DEVICE);
        mServerOperate.startServer();
    }

    private void registReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Network.CONNECTIVITY_CHANGE_ACTION);
        filter.addAction(MSG_VIRTUAL_KEY_SERVER_ACTIVE);

        filter.addAction(SessionPreferenceOfIntent.ACT_COMPILE_GRAMMER_TO_TV);
        // recognize
        filter.addAction(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_START_TALK_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_STOP_TALK_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_CANCEL_TALK_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_PUT_CUSTOM_TEXT_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_SET_PROTOCAL_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_PLAY_TTS_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_STOP_TTS_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.ACT_COMPILE_GRAMMER_TO_TV);

        // control
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_START_SCANNER_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_STOP_SCANNER_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_CONNECT_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_DISCONNECT_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_START_MACHINE_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_STOP_MACHINE_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_CONTROL_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_VOLUME_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_CHANNEL_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_SEND_DATA_TO_SERVER_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_START_CHECK_IP_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_CONTROL_STOP_CHECK_IP_TO_TV);
        // server
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_SERVER_HAS_CONNECT_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_SERVER_START_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_SERVER_STOP_TO_TV);
        filter.addAction(SessionPreferenceOfIntent.OPERATE_ACT_SERVER_SEND_DATA_TO_CONTROL_TO_TV);

        // show
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_WAITING);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_WEATHER_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_WEB_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_TRANSLATION_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_STOCK_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_MUSIC_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_PROG_RECOMMEND);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_PROG_SEARCH_RESULT);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_CHANNEL_PROG_LIST);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_ROUTE_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_POSITION_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_TALK_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_ERROR_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_APP_LAUNCH);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_APP_UNINSTALL);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_APP_EXIT);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_SETTING);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_REMINDER_CONFIRM);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_REMINDER_OK);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_POI_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_MULTIPLE_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_UI_HANDLE_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_NOTE_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_ALARM_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_APP_MUTIPLEP_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_INPUT_CONTENT_WEIBO);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_WEIBO_OK);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_CHANNEL_SWITCH_SHOW);
        filter.addAction(SessionPreferenceOfIntent.VALUE_TYPE_SHOP_SHOW);
        filter.setPriority(10000);
        filter.addCategory(getPackageName());
        registerReceiver(mBroadcastReceiver, filter);
    }

    private void unregistReceiver() {
        try {
            unregisterReceiver(mBroadcastReceiver);
        } catch (Exception e) {
        }
    }

    private void startTalk() {
        LogUtil.d(TAG, "startTalk :method     " + mInteractiveMethod);
        if (mInteractiveMethod) {
            mVoiceAssistant.start();
        } else {
            showMessage(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_START_TALK_FROM_TV);
        }

    }

    private void stopTalk() {
        if (mInteractiveMethod) {
            mVoiceAssistant.stop();
        } else {
            showMessage(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_STOP_TALK_FROM_TV);
        }
    }

    private void cancelTalk() {
        if (mInteractiveMethod) {
            mVoiceAssistant.cancel();
        } else {
            showMessage(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_CANCEL_TALK_FROM_TV);
        }
    }

    private void putCustomText(String text) {
        if (mInteractiveMethod) {
            mVoiceAssistant.putCustomText(text);
        } else {
            Bundle extras = new Bundle();
            extras.putString(SessionPreferenceOfIntent.KEY_TEXT, text);
            showMessage(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_PUT_CUSTOM_TEXT_FROM_TV, extras);
        }
    }

    private void setProtocal(String protocal) {
        LogUtil.d(TAG, "setProtocal protocal:" + protocal);
        if (mInteractiveMethod) {
            mVoiceAssistant.setProtocal(protocal);
        } else {
            Bundle extras = new Bundle();
            extras.putString(SessionPreferenceOfIntent.KEY_PROTOCAL, protocal);
            showMessage(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_SET_PROTOCAL_FROM_TV, extras);
        }
    }

    private void onTalkStart() {
        LogUtil.d(TAG, "onTalkStart");
        showMessage(TALK_EVENT_ON_START);
    }

    private void onTalkStop() {
        LogUtil.d(TAG, "onTalkStop");
        showMessage(TALK_EVENT_ON_STOP);
    }

    private void onRecordingStart() {
        LogUtil.d(TAG, "onRecordingStart");
        showMessage(TALK_EVENT_ON_RECORDING_START);
    }

    private void onUpdateVolume(int volume) {
        // LogUtil.d(TAG,"volume " + volume);
        Bundle extras = new Bundle();
        extras.putInt(TALK_DATA_VOLUME, volume);
        showMessage(TALK_EVENT_ON_UPDATE_VOLUME, extras);
    }

    private void onTalkCancel() {
        LogUtil.d(TAG, "onTalkCancel");
        showMessage(TALK_EVENT_ON_CANCEL);
    }

    private void onSessionProtocal(String protocal) {
        LogUtil.d(TAG, "onSessionProtocal:" + protocal);
        Bundle extras = new Bundle();
        extras.putString(TALK_DATA_PROTOCAL, protocal);
        showMessage(TALK_EVENT_ON_SESSION_PROTOCAL, extras);
    }

    private void playTTS(String tts) {
        // LogUtil.d(TAG, "playTTS tts=" + tts);
        // if (mTTSPlayer == null) {
        // LogUtil.e(TAG, "TTSPlayer instance is null!");
        // } else if (!TextUtils.isEmpty(tts)) {
        // if (mInteractiveMethod) {
        // tts = tts.toLowerCase(Locale.getDefault());
        // // tts = tts.replaceAll("[^\u4e00-\u9fa5]", "");
        // mTTSPlayer.play("。" + tts + "。");
        // } else {
        // Bundle extras = new Bundle();
        // extras.putString(SessionPreferenceOfIntent.KEY_TTS, tts);
        // showMessage(
        // SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_PLAY_TTS_FROM_TV,
        // extras);
        // }
        // }
    }

    private void stopTTS() {
        // LogUtil.d(TAG, "stopTTS");
        // if (mTTSPlayer != null) {
        // if (mInteractiveMethod) {
        // mTTSPlayer.stop();
        // } else {
        // showMessage(SessionPreferenceOfIntent.ACT_RECOGNIZE_OPERATE_STOP_TTS_FROM_TV);
        // }
        // }
    }

    private void onConnectClient(String client) {
        LogUtil.d(TAG, "onConnectClient client:" + client);
        showMessage(MOBILE_CONTROL_CONNECTION);
    }

    public void onDisconnectClient(String client) {
        LogUtil.d(TAG, "onDisconnectClient client:" + client);
        showMessage(MOBILE_CONTROL_DISCONNECTION);
    }

    private void startAssistant() {
        // LogUtil.d(TAG, "startAssistant");
        // Bundle extras = new Bundle();
        // extras.putBoolean(WindowService.BUNDLE_DATA_FROM_MOBILE_CONTROL,
        // true);
        // showMessage(MessageReceiver.ACTION_START_TALK, extras);
        // showMessage(MessageReceiver.ACTION_STOP_TALK, extras);
    }

    private void exitAssistant() {
        LogUtil.d(TAG, "exitAssistant");
        showMessage(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    }

    private void onVirtureKeyBack() {
        LogUtil.d(TAG, "onVirtureKeyBack");
        showMessage(WindowService.MSG_VIRTUAL_KEY_BACK);
    }

    private void onVirtureKeyCenter() {
        LogUtil.d(TAG, "onVirtureKeyCenter");
        showMessage(WindowService.MSG_VIRTUAL_KEY_CENTER);
    }

    private void onVirtureKeyLeft() {
        LogUtil.d(TAG, "onVirtureKeyLeft");
        showMessage(WindowService.MSG_VIRTUAL_KEY_LEFT);
    }

    private void onVirtureKeyRight() {
        LogUtil.d(TAG, "onVirtureKeyRight");
        showMessage(WindowService.MSG_VIRTUAL_KEY_RIGHT);
    }

    private void onVirtureKeyUp() {
        LogUtil.d(TAG, "onVirtureKeyUp");
        showMessage(WindowService.MSG_VIRTUAL_KEY_UP);
    }

    private void onVirtureKeyDown() {
        LogUtil.d(TAG, "onVirtureKeyDown");
        showMessage(WindowService.MSG_VIRTUAL_KEY_DOWN);
    }

    public static IDataControl getDataControl() {
        return mDataControl;
    }

    public static ArrayList<String> getSupportList(boolean hasNetWork) {
        if (hasNetWork) {
            return mOnlineSupportList;
        } else {
            return mOfflineSupportList;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.d(TAG, "onStartCommand:" + intent);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        LogUtil.d(TAG, "onDestroy");
        mServiceCompileLooper.quit();
        mDataControl = null;
        mServerOperate.stopServer();
        mVoiceAssistant.release();
        mServerOperate = null;
        mVoiceAssistant = null;
        mTalkService = null;
        unregistReceiver();
        super.onDestroy();
    }

    private void showMessage(String message, Bundle extras) {
        Intent intent = new Intent(message);
        if (extras != null) intent.putExtras(extras);
        intent.addCategory(getPackageName());
        sendBroadcast(intent);
    }

    private void showMessage(String message) {
        showMessage(message, null);
    }

    static void changeVolume(Context ctx, boolean add) {
        AudioManager am = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);

        am.adjustStreamVolume(AudioManager.STREAM_MUSIC, add ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER,
                AudioManager.FLAG_SHOW_UI);
    }
}
